package titt.service.content.listener;

import titt.io.socket.in.TITTInputStream;
import titt.io.socket.out.TITTOutputStream;
import titt.util.io.pipe.PipeListener;

public class IOTimeoutListener implements PipeListener {
	
	private final PipeListener listener;
	
	private boolean once = true;
	private long success;
	private final TITTInputStream in;
	private final TITTOutputStream out;
		
	public IOTimeoutListener(TITTInputStream in, TITTOutputStream out, PipeListener listener) {
		this.listener = listener;
		this.out = out;
		this.in = in;

		synchronized (this) {
			success = System.currentTimeMillis();
		}
		
		IOGarbageCollector.get().add(this);
	}
	
	private synchronized boolean once() {
		return once && !(once = false);
	}

	public synchronized long getLastSuccess() {
		return success;
	}
	
	public synchronized void kill() {
		try {
			onError();
			
//			System.out.println("killing...");
			
			if(in != null) in.close();
			if(out != null) out.close();
		}
		catch(Exception e) {}
	}
	
	@Override
	public void onComplete(int total) {
		if(!once()) return;
		
		IOGarbageCollector.get().remove(this);
		
		if(listener != null)
			listener.onComplete(total);
	}

	@Override
	public void onConnectionUpdate(int read, int total) {
		synchronized (this) {
			success = System.currentTimeMillis();
		}

		if(listener != null)
			listener.onConnectionUpdate(read, total);
	}

	@Override
	public void onError() {
		if(!once()) return;
		
		IOGarbageCollector.get().remove(this);
		
		if(listener != null)
			listener.onError();
	}

	@Override
	public void onInitiate(int total) {
		synchronized (this) {
			success = System.currentTimeMillis();
		}
		
		if(listener != null)
			listener.onInitiate(total);
	}
}
